package com.sls.web.manager.action.game;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;

import com.sls.web.manager.action.SuperAction;
import com.sls.web.manager.common.Constants;
import com.sls.web.manager.execption.ManagerException;
import com.sls.web.manager.game.pojo.EnLinkProduct;
import com.sls.web.manager.game.pojo.EnLinkProductAreaServer;
import com.sls.web.manager.game.querybean.EnLinkProductAreaServerQuery;
import com.sls.web.manager.game.querybean.EnLinkProductQuery;
import com.sls.web.manager.game.service.EnLinkProductService;
import com.sls.web.manager.page.Pagination;

/**
 * 恩联产品管理
 * 
 * @author cx
 * 
 */
@InterceptorRefs({
		@InterceptorRef(value = "defaultStack", params = { "maximumSize",
				"2048000", "allowedTypes",
				"text/plain,application/excel,application/vnd.ms-excel" }),
		@InterceptorRef(value = "defalutStackSet") })
public class EnLinkAction extends SuperAction {

	private static final long serialVersionUID = -5081035034707901621L;
	@Resource(name = "enLinkProductService")
	private EnLinkProductService enLinkService;
	private EnLinkProductQuery enLinkQuery;
	private EnLinkProductAreaServerQuery enLinkAreaServerQuery;
	private EnLinkProduct enLinkProduct;
	private EnLinkProductAreaServer areaServer;
	private String productId;
	private String proId;
	private String productName;
	private String productState;
	private String productType;
	private Pagination<?> page;
	private String supplierId;
	private int priceRatio;
	private File productExcel;// 获取上传文件
	private String productExcelFileName;// 获取上传文件名称
	private String productExcelContentType;// 获取上传文件类型
	private File asExcel;// 获取上传文件
	private String asExcelFileName;// 获取上传文件名称

	/**
	 * 添加产品
	 * 
	 * @return
	 */
	public String add() {
		return INPUT;
	}

	/**
	 * 添加区服
	 * 
	 * @return
	 */
	public String addAs() {
		return INPUT;
	}

	/**
	 * 保存产品信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String save() throws Exception {
		try {
			this.enLinkService.save(enLinkProduct, getCurrentOperator());
			this.redirectionUrl = "en_link!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	public String toEdit() throws Exception {
		try {
			enLinkProduct = this.enLinkService.queryByProductId(productId,
					getCurrentOperator());
		} catch (ManagerException e) {
			addActionError(e.getMessage());
		}
		return INPUT;
	}

	public String edit() throws Exception {
		try {
			this.enLinkService.update(enLinkProduct, getCurrentOperator());

			if (enLinkQuery == null) {
				enLinkQuery = new EnLinkProductQuery();
				enLinkQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
				enLinkQuery.setPageSize(Constants.INIT_PAGESIZE);
			}
			if (StringUtils.isNotEmpty(proId)) {
				enLinkQuery.setProductId(proId);
			}
			if (StringUtils.isNotEmpty(productName)) {
				enLinkQuery.setProductName(productName);
			}
			if (StringUtils.isNotEmpty(productState)) {
				enLinkQuery.setProductState(productState);
			}
			if (StringUtils.isNotEmpty(productType)) {
				enLinkQuery.setProductType(productType);
			}
		} catch (ManagerException e) {
			addActionError(e.getMessage());
		}
		return list();
	}

	/**
	 * 保存区服信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String saveAs() throws Exception {
		try {
			this.enLinkService.saveAreaServer(areaServer, getCurrentOperator());
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 恩联产品列表显示
	 * 
	 * @return
	 * @throws Exception
	 */
	public String list() throws Exception {
		if (enLinkQuery == null) {
			enLinkQuery = new EnLinkProductQuery();
			enLinkQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
			enLinkQuery.setPageSize(Constants.INIT_PAGESIZE);
		}
		try {
			page = this.enLinkService.queryEnLinkProduct(enLinkQuery,
					getCurrentOperator());
		} catch (ManagerException e) {
			addActionError(e.getMessage());
		}

		return LIST;
	}

	/**
	 * 区服列表
	 * 
	 * @return
	 * @throws Exception
	 */
	public String areaServerList() throws Exception {
		if (enLinkAreaServerQuery == null) {
			enLinkAreaServerQuery = new EnLinkProductAreaServerQuery();
			enLinkAreaServerQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
			enLinkAreaServerQuery.setPageSize(Constants.INIT_PAGESIZE);
		}
		try {
			page = this.enLinkService.queryEnLinkProductAreaServer(
					enLinkAreaServerQuery, getCurrentOperator());
		} catch (ManagerException e) {
			addActionError(e.getMessage());
		}
		return "aslist";
	}

	/**
	 * 恩联商品审核
	 * 
	 * @return
	 * @throws Exception
	 */
	public String audit() throws Exception {
		try {
			this.enLinkService.confirmAudit(supplierId, priceRatio,
					getCurrentOperator());
			redirectionUrl = "en_link!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 批量上架
	 * 
	 * @return
	 * @throws Exception
	 */
	public String batchOnline() throws Exception {
		try {
			this.enLinkService.batchOnline("1", getCurrentOperator());
			redirectionUrl = "en_link!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 批量下架
	 * 
	 * @return
	 * @throws Exception
	 */
	public String batchOffline() throws Exception {
		try {
			this.enLinkService.batchOffline("0", getCurrentOperator());
			redirectionUrl = "en_link!list.htm";
		} catch (ManagerException e) {
			flag = false;
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	/**
	 * 导入产品excel文件
	 * 
	 * @return
	 * @throws Exception
	 */
	public String importProductFile() throws Exception {
		if (StringUtils.isEmpty(productExcelFileName)) {
			flag = false;
			addActionError("请选择要导入的文件!");
			return SUCCESS;
		}
		if (!productExcelFileName.endsWith(".xls")
				&& !productExcelFileName.endsWith(".xlsx")) {
			flag = false;
			addActionError("文件类型有误!<br>必须为excel文件!");
			return SUCCESS;
		}
		InputStream is = null;
		try {
			is = new FileInputStream(productExcel);
		} catch (FileNotFoundException e1) {
			addActionError(e1.getMessage());
		}
		List<EnLinkProduct> list = null;
		try {
			if (is != null) {
				if (productExcelFileName.endsWith(".xls")) {
					list = this.extractListFromXLS2003(is);
				} else if (productExcelFileName.endsWith(".xlsx")) {
					list = this.extractListFromXLS2007(is);
				}
			}
		} catch (IOException e) {
			addActionError(e.getMessage());
		}
		String message = "";
		if (list != null && !list.isEmpty()) {
			for (EnLinkProduct enlink : list) {
				if (enlink != null) {
					try {
						this.enLinkService.save(enlink, getCurrentOperator());
					} catch (ManagerException e) {
						message += enlink.getProductId() + "," + e.getMessage()
								+ "<br>";
						continue;
					}
				}
			}
		}
		if (StringUtils.isNotEmpty(message)) {
			flag = false;
			addActionError(message);
		}
		this.redirectionUrl = "en_link!list.htm";
		return SUCCESS;
	}

	/**
	 * 导入区服信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String improtAreaServerFile() throws Exception {
		if (StringUtils.isEmpty(asExcelFileName)) {
			flag = false;
			addActionError("请选择要导入的文件!");
			return SUCCESS;
		}
		if (!asExcelFileName.endsWith(".xls")
				&& !asExcelFileName.endsWith(".xlsx")) {
			flag = false;
			addActionError("文件类型有误!<br>必须为excel文件.");
			return SUCCESS;
		}
		InputStream is = null;
		try {
			is = new FileInputStream(asExcel);
		} catch (FileNotFoundException e1) {
			addActionError(e1.getMessage());
		}
		List<EnLinkProductAreaServer> list = null;
		try {
			if (is != null) {
				if (asExcelFileName.endsWith(".xls")) {
					list = this.extractFromXLS2003(is);
				} else if (asExcelFileName.endsWith(".xlsx")) {
					list = this.extractFromXLS2007(is);
				}
			}
		} catch (IOException e) {
			addActionError(e.getMessage());
		}

		// 先删除区服信息，再重新插入
		this.enLinkService.deleteAreaServer(getCurrentOperator());
		String message = "";
		if (list != null && !list.isEmpty()) {
			for (EnLinkProductAreaServer enlink : list) {
				if (enlink != null) {
					try {
						this.enLinkService.saveAreaServer(enlink,
								getCurrentOperator());
					} catch (ManagerException e) {
						message += enlink.getProductId() + ","
								+ enlink.getBigAreaName() + "--"
								+ enlink.getSmallServerName() + ","
								+ e.getMessage() + "<br>";
						continue;
					}
				}
			}
		}
		if (StringUtils.isNotEmpty(message)) {
			flag = false;
			addActionError(message);
		}
		this.redirectionUrl = "en_link!areaServerList.htm";
		return SUCCESS;
	}

	/**
	 * 解析excel2003文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	private List<EnLinkProduct> extractListFromXLS2003(InputStream is)
			throws IOException {
		List<EnLinkProduct> list = new ArrayList<EnLinkProduct>();
		EnLinkProduct enlink = null;
		HSSFWorkbook workbook = new HSSFWorkbook(is); // 创建对Excel工作簿文件的引用
		for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
			if (null != workbook.getSheetAt(numSheets)) {
				HSSFSheet aSheet = workbook.getSheetAt(numSheets); // 获得一个sheet
				for (int rowNumOfSheet = 1; rowNumOfSheet <= aSheet
						.getLastRowNum(); rowNumOfSheet++) {
					if (null != aSheet.getRow(rowNumOfSheet)) {
						enlink = new EnLinkProduct();
						List<String> cellList = new ArrayList<String>();
						HSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 获得一行
						for (int cellNumOfRow = 0; cellNumOfRow <= aRow
								.getLastCellNum(); cellNumOfRow++) {
							if (null != aRow.getCell(cellNumOfRow)) {
								HSSFCell aCell = aRow.getCell(cellNumOfRow); // 获得列值
								if (aCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
									double parvalue = aCell
											.getNumericCellValue();
									cellList.add(String.valueOf(parvalue));
								} else if (aCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
									boolean flag = aCell.getBooleanCellValue();
									cellList.add(String.valueOf(flag));
								} else {
									cellList.add(aCell.getStringCellValue());
								}

								if (cellList.size() > 0) {
									enlink.setProductId(cellList.get(0));
								}
								if (cellList.size() > 1) {
									enlink.setProductName(cellList.get(1));
								}
								if (cellList.size() > 2) {
									enlink.setProductParvalue(cellList.get(2));
								}
								if (cellList.size() > 3) {
									enlink.setProductInPrice(cellList.get(3));
								}
								if (cellList.size() > 4) {
									if ("2.0".equals(cellList.get(4))) {
										enlink.setProductType("2");
									} else if ("1.0".equals(cellList.get(4))) {
										enlink.setProductState("1");
									} else {
										enlink.setProductType(cellList.get(4));
									}
								}
								if (cellList.size() > 5) {
									if ("1.0".equals(cellList.get(5))) {
										enlink.setProductState("1");
									} else if ("0.0".equals(cellList.get(5))) {
										enlink.setProductState("0");
									} else {
										enlink.setProductState(cellList.get(5));
									}
								}
								if (cellList.size() > 6) {
									enlink.setRemark(cellList.get(6));
								}
								if (cellList.size() > 7) {
									enlink.setT_remark(cellList.get(7));
								}
							}
						}

					}
					list.add(enlink);
				}
			}
		}
		return list;
	}

	/**
	 * 解析excel2007文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	private List<EnLinkProduct> extractListFromXLS2007(InputStream is)
			throws IOException {
		List<EnLinkProduct> list = new ArrayList<EnLinkProduct>();
		EnLinkProduct enlink = null;
		// 构造 XSSFWorkbook 对象，strPath
		// 传入文件路径
		XSSFWorkbook xwb = new XSSFWorkbook(is);
		// 循环工作表Sheet
		for (int numSheet = 0; numSheet < xwb.getNumberOfSheets(); numSheet++) {
			XSSFSheet xSheet = xwb.getSheetAt(numSheet);
			if (xSheet == null) {
				continue;
			}
			// 循环行Row
			for (int rowNum = 1; rowNum <= xSheet.getLastRowNum(); rowNum++) {
				enlink = new EnLinkProduct();
				XSSFRow xRow = xSheet.getRow(rowNum);
				if (xRow == null) {
					continue;
				}
				List<String> cellList = new ArrayList<String>();
				// 循环列Cell
				for (int cellNum = 0; cellNum <= xRow.getLastCellNum(); cellNum++) {
					XSSFCell xCell = xRow.getCell(cellNum);

					if (xCell == null) {
						continue;
					}
					if (xCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
						boolean flag = xCell.getBooleanCellValue();
						cellList.add(String.valueOf(flag));
					} else if (xCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
						double parvalue = xCell.getNumericCellValue();
						cellList.add(String.valueOf(parvalue));
					} else {
						cellList.add(xCell.getStringCellValue());
					}
					if (cellList.size() > 0) {
						enlink.setProductId(cellList.get(0));
					}
					if (cellList.size() > 1) {
						enlink.setProductName(cellList.get(1));
					}
					if (cellList.size() > 2) {
						enlink.setProductParvalue(cellList.get(2));
					}
					if (cellList.size() > 3) {
						enlink.setProductInPrice(cellList.get(3));
					}
					if (cellList.size() > 4) {
						if ("2.0".equals(cellList.get(4))) {
							enlink.setProductType("2");
						} else if ("1.0".equals(cellList.get(5))) {
							enlink.setProductState("1");
						} else {
							enlink.setProductType(cellList.get(4));
						}
					}
					if (cellList.size() > 5) {
						if ("1.0".equals(cellList.get(5))) {
							enlink.setProductState("1");
						} else if ("0.0".equals(cellList.get(5))) {
							enlink.setProductState("0");
						} else {
							enlink.setProductState(cellList.get(5));
						}
					}
					if (cellList.size() > 6) {
						enlink.setRemark(cellList.get(6));
					}
					if (cellList.size() > 7) {
						enlink.setT_remark(cellList.get(7));
					}
				}
				list.add(enlink);
			}
		}
		return list;
	}

	/**
	 * 解析区服文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	private List<EnLinkProductAreaServer> extractFromXLS2003(InputStream is)
			throws IOException {
		List<EnLinkProductAreaServer> list = new ArrayList<EnLinkProductAreaServer>();
		EnLinkProductAreaServer enlink = null;
		HSSFWorkbook workbook = new HSSFWorkbook(is); // 创建对Excel工作簿文件的引用
		for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
			if (null != workbook.getSheetAt(numSheets)) {
				HSSFSheet aSheet = workbook.getSheetAt(numSheets); // 获得一个sheet
				for (int rowNumOfSheet = 1; rowNumOfSheet <= aSheet
						.getLastRowNum(); rowNumOfSheet++) {
					if (null != aSheet.getRow(rowNumOfSheet)) {
						enlink = new EnLinkProductAreaServer();
						List<String> cellList = new ArrayList<String>();
						HSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 获得一行
						for (int cellNumOfRow = 0; cellNumOfRow <= aRow
								.getLastCellNum(); cellNumOfRow++) {
							if (null != aRow.getCell(cellNumOfRow)
									&& !"".equals(aRow.getCell(cellNumOfRow))) {
								HSSFCell aCell = aRow.getCell(cellNumOfRow); // 获得列值
								if (aCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
									double parvalue = aCell
											.getNumericCellValue();
									cellList.add(String.valueOf(parvalue));
								} else if (aCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
									boolean flag = aCell.getBooleanCellValue();
									cellList.add(String.valueOf(flag));
								} else {
									cellList.add(aCell.getStringCellValue());
								}

								if (cellList.size() > 0) {
									enlink.setProductId(cellList.get(0));
								}
								if (cellList.size() > 1) {
									enlink.setBigAreaId(cellList.get(1));
								}
								if (cellList.size() > 2) {
									enlink.setBigAreaName(cellList.get(2));
								}
								if (cellList.size() > 3) {
									enlink.setSmallServerId(cellList.get(3));
								}
								if (cellList.size() > 4) {
									enlink.setSmallServerName(cellList.get(4));
								}
							} else {
								cellList.add("");
							}
						}

					}
					list.add(enlink);
				}
			}
		}
		return list;
	}

	/**
	 * 解析区服文件
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	private List<EnLinkProductAreaServer> extractFromXLS2007(InputStream is)
			throws IOException {
		List<EnLinkProductAreaServer> list = new ArrayList<EnLinkProductAreaServer>();
		EnLinkProductAreaServer enlink = null;
		// 构造 XSSFWorkbook 对象，strPath
		// 传入文件路径
		XSSFWorkbook xwb = new XSSFWorkbook(is);
		// 循环工作表Sheet
		for (int numSheet = 0; numSheet < xwb.getNumberOfSheets(); numSheet++) {
			XSSFSheet xSheet = xwb.getSheetAt(numSheet);
			if (xSheet == null) {
				continue;
			}
			// 循环行Row
			for (int rowNum = 1; rowNum <= xSheet.getLastRowNum(); rowNum++) {
				enlink = new EnLinkProductAreaServer();
				XSSFRow xRow = xSheet.getRow(rowNum);
				if (xRow == null) {
					continue;
				}
				List<String> cellList = new ArrayList<String>();
				// 循环列Cell
				for (int cellNum = 0; cellNum <= xRow.getLastCellNum(); cellNum++) {
					XSSFCell xCell = xRow.getCell(cellNum);

					if (xCell == null) {
						cellList.add("");
						continue;
					}
					if (xCell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
						boolean flag = xCell.getBooleanCellValue();
						cellList.add(String.valueOf(flag));
					} else if (xCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
						double parvalue = xCell.getNumericCellValue();
						cellList.add(String.valueOf(parvalue));
					} else {
						cellList.add(xCell.getStringCellValue());
					}
					if (cellList.size() > 0) {
						enlink.setProductId(cellList.get(0));
					}
					if (cellList.size() > 1) {
						enlink.setBigAreaId(cellList.get(1));
					}
					if (cellList.size() > 2) {
						enlink.setBigAreaName(cellList.get(2));
					}
					if (cellList.size() > 3) {
						enlink.setSmallServerId(cellList.get(3));
					}
					if (cellList.size() > 4) {
						enlink.setSmallServerName(cellList.get(4));
					}

				}
				list.add(enlink);
			}
		}
		return list;
	}

	public EnLinkProductQuery getEnLinkQuery() {
		return enLinkQuery;
	}

	public void setEnLinkQuery(EnLinkProductQuery enLinkQuery) {
		this.enLinkQuery = enLinkQuery;
	}

	public Pagination<?> getPage() {
		return page;
	}

	public void setPage(Pagination<?> page) {
		this.page = page;
	}

	public EnLinkProduct getEnLinkProduct() {
		return enLinkProduct;
	}

	public void setEnLinkProduct(EnLinkProduct enLinkProduct) {
		this.enLinkProduct = enLinkProduct;
	}

	public String getSupplierId() {
		return supplierId;
	}

	public void setSupplierId(String supplierId) {
		this.supplierId = supplierId;
	}

	public int getPriceRatio() {
		return priceRatio;
	}

	public void setPriceRatio(int priceRatio) {
		this.priceRatio = priceRatio;
	}

	public EnLinkProductAreaServerQuery getEnLinkAreaServerQuery() {
		return enLinkAreaServerQuery;
	}

	public void setEnLinkAreaServerQuery(
			EnLinkProductAreaServerQuery enLinkAreaServerQuery) {
		this.enLinkAreaServerQuery = enLinkAreaServerQuery;
	}

	public File getProductExcel() {
		return productExcel;
	}

	public void setProductExcel(File productExcel) {
		this.productExcel = productExcel;
	}

	public String getProductExcelFileName() {
		return productExcelFileName;
	}

	public void setProductExcelFileName(String productExcelFileName) {
		this.productExcelFileName = productExcelFileName;
	}

	public String getProductExcelContentType() {
		return productExcelContentType;
	}

	public void setProductExcelContentType(String productExcelContentType) {
		this.productExcelContentType = productExcelContentType;
	}

	public File getAsExcel() {
		return asExcel;
	}

	public void setAsExcel(File asExcel) {
		this.asExcel = asExcel;
	}

	public String getAsExcelFileName() {
		return asExcelFileName;
	}

	public void setAsExcelFileName(String asExcelFileName) {
		this.asExcelFileName = asExcelFileName;
	}

	public EnLinkProductAreaServer getAreaServer() {
		return areaServer;
	}

	public void setAreaServer(EnLinkProductAreaServer areaServer) {
		this.areaServer = areaServer;
	}

	public String getProductId() {
		return productId;
	}

	public void setProductId(String productId) {
		this.productId = productId;
	}

	public String getProId() {
		return proId;
	}

	public void setProId(String proId) {
		this.proId = proId;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public String getProductState() {
		return productState;
	}

	public void setProductState(String productState) {
		this.productState = productState;
	}

	public String getProductType() {
		return productType;
	}

	public void setProductType(String productType) {
		this.productType = productType;
	}

}
